package com.example.familytreebe.controller;

import com.example.familytreebe.entity.Relationship;
import com.example.familytreebe.service.RelationshipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/relationships")
public class RelationshipController {
    private final RelationshipService relationshipService;

    @Autowired
    public RelationshipController(RelationshipService relationshipService) {
        this.relationshipService = relationshipService;
    }

    // 保存关系
    @PostMapping
    public Relationship saveRelationship(@RequestBody Relationship relationship) {
        return relationshipService.saveRelationship(relationship);
    }

    // 根据 ID 获取关系
    @GetMapping("/{id}")
    public ResponseEntity<?> getRelationshipById(@PathVariable Long id) {
        Optional<Relationship> relationship = relationshipService.getRelationshipById(id);
        return relationship.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    // 获取所有关系
    @GetMapping
    public List<Relationship> getAllRelationships() {
        return relationshipService.getAllRelationships();
    }

    // 删除关系
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteRelationship(@PathVariable Long id) {
        relationshipService.deleteRelationship(id);
        return ResponseEntity.ok("关系删除成功");
    }

    // 根据人员 ID 获取关系
    @GetMapping("/person/{personId}")
    public List<Relationship> getRelationshipsByPersonId(@PathVariable Long personId) {
        return relationshipService.getRelationshipsByPersonId(personId);
    }

    // 根据人员 ID 和关系类型获取关系
    @GetMapping("/person/{personId}/type/{type}")
    public List<Relationship> getRelationshipsByPersonIdAndType(@PathVariable Long personId, @PathVariable String type) {
        return relationshipService.getRelationshipsByPersonIdAndType(personId, type);
    }
}